#!/usr/bin/env bash
common_abspath() (
  echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
)
common_bench_cmd() (
  # Benchmark a command.
  #
  # $1: command to benchmark
  # $2: where to append write results to. Default: /dev/null.
  #
  # Result format:
  #
  # cmd <command run>
  # time <time in seconds to finish>
  # exit_status <exit status>
  cmd="$1"
  results_file="${2:-/dev/null}"
  printf 'cmd ' >> "$results_file"
  env time --append -f 'time %e' --output="$results_file" "${root_dir}/eeval" -a "$cmd" "$results_file"
  printf "exit_status $?\n" >> "$results_file"
)
set_common_vars() {
  arch="$1"
  gem5="${2:-false}"
  case "$arch" in
    a|arm)
      arch=arm
      ;;
    A|aarch64)
      arch=aarch64
      ;;
    m|mips64)
      arch=mips64
      ;;
    x|x86_64)
      arch=x86_64
      ;;
    *)
      printf "unknown arch: ${arch}\n" 1>&2
      exit 2
      ;;
  esac
  common_suffix="${3:-}"
  buildroot_dir="${root_dir}/buildroot"
  arch_dir="$arch"
  if [ -n "$common_suffix" ]; then
    arch_dir="${arch_dir}-${common_suffix}"
  fi
  out_arch_dir="${out_dir}/${arch_dir}"
  buildroot_out_dir="${out_arch_dir}/buildroot"
  build_dir="${buildroot_out_dir}/build"
  images_dir="${buildroot_out_dir}/images"
  host_dir="${buildroot_out_dir}/host"
  qemu_out_dir="${out_arch_dir}/qemu"
  gem5_run_out_dir="${out_arch_dir}/gem5"
  m5out_dir="${gem5_run_out_dir}/m5out"
  if "$gem5"; then
    common_out_run_dir="$gem5_run_out_dir"
    common_trace_txt_file="${m5out_dir}/trace.txt"
  else
    common_out_run_dir="$qemu_out_dir"
    common_trace_txt_file="${common_out_run_dir}/trace.txt"
  fi
}
common_mkdir() (
  mkdir -p \
    "$build_dir" \
    "$gem5_out_dir" \
    "$qemu_out_dir" \
    "$p9_dir" \
  ;
)
root_dir="$(pwd)"
out_dir="${root_dir}/out"
common_bench_boot="${out_dir}/bench-boot.txt"
data_dir="${root_dir}/data"
p9_dir="${data_dir}/9p"
readfile_file="${data_dir}/readfile"
common_dir="${out_dir}/common"
gem5_out_dir="${common_dir}/gem5"
f="${data_dir}/cli"
if [ -f "$f" ]; then
  . "$f"
fi
# Default arch.
arch=x86_64
gem5=false
